package com.example.demo.module.mq;

import com.example.demo.entity.Order;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeoutException;

/**
 * 通过mq创建订单
 */
@Service
public class CreateOrderSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *
     * @param queueName
     */
    public void sendOrder(String queueName, Order order) {
        rabbitTemplate.convertAndSend(queueName,order);
    }

    public int query() {
        Connection connection = null;
        Channel channel = null;
        int messageCount = 0;
        try {
            connection = rabbitTemplate.getConnectionFactory().createConnection();
            channel = connection.createChannel(false);

            AMQP.Queue.DeclareOk declareOk = channel.queueDeclare("create_order_queue",true,false,false,null);
            messageCount = declareOk.getMessageCount();
            System.out.println("messageCount="+messageCount);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
            connection.close();
        }
        return messageCount;
    }
}
